<template>
    <div class="toolBox">
        <div class="header-content">

            <img src="../assets/images/tool/logoText.png" alt="" class="logoText" @click="goBackHome">
            <div class="user-info">

                <div class="freeTimesValue"> {{freeTimesValue}}</div>
                <el-tag class="toBeMember" type="warning" @click="toBeMember()">⭐ 成为会员</el-tag>
                <span class="name" v-if="!userInfoDetail" @click="handleToolClick()">请登录</span>
                <el-dropdown class="avatar-container right-menu-item hover-effect" trigger="click" v-else>
                    <div class="avatar-wrapper">
                        <span class="name">{{userInfoDetail.userName}}</span>
                    </div>
                    <el-dropdown-menu slot="dropdown">
                        <el-dropdown-item @click.native="logout">
                            <span>退出登录</span>
                        </el-dropdown-item>
                    </el-dropdown-menu>
                </el-dropdown>

            </div>
        </div>

        <div class="contentBox">
            <router-view> </router-view>
        </div>

        <!-- 登录模态框 -->
        <el-dialog :visible.sync="loginModalVisible" width="700px" :before-close="hideLoginModal" class="loginDialog">
            <el-row :gutter="20" class="qrcodeBox">
                <!-- 微信扫码登录 -->
                <el-col :span="12">
                    <div class="qrcode-wrapper">
                        <div class="qrcode-header">
                            <h3>微信扫码登录</h3>
                            <p>打开微信扫一扫</p>
                        </div>
                        <div class="qrcode-content">
                            <!-- <img src=""
                     alt="微信二维码"
                     class="qrcode-image"> -->
                            <!-- <div v-if="qrcodeStatus" class="qrcode-status"> -->
                            <!-- <i class="el-icon-loading"></i> -->
                            <span>正在开发中</span>
                            <!-- </div> -->
                        </div>
                        <p class="qrcode-footer">请使用微信扫描二维码登录</p>
                    </div>
                </el-col>

                <!-- 手机验证登录 -->
                <el-col :span="12">
                    <div class="phone-login">
                        <div class="phone-login-header">
                            <h2>手机验证登录</h2>
                        </div>
                        <el-form :model="loginForm" :rules="rules" ref="loginForm">
                            <el-form-item label="手机号码" prop="phone">
                                <el-input v-model="loginForm.phone" placeholder="请输入11位手机号" maxlength="11" @input="setIsPhone"></el-input>
                            </el-form-item>
                            <el-form-item label="验证码" prop="code">
                                <div style="position: relative;">
                                    <el-input v-model="loginForm.code" placeholder="6位验证码" maxlength="6"></el-input>
                                    <span v-if="isCodeSent" style="position: absolute;right:10px">{{isCodeSentSecond}}秒后重新获取</span>
                                    <el-button v-else style="position: absolute;right:0px" type="primary" id="captcha-button"
                                        :disabled="!isPhone">获取验证码</el-button>
                                </div>
                            </el-form-item>
                            <el-button type="primary" @click="doLogin" class="login-button">立即登录</el-button>

                        </el-form>
                    </div>
                </el-col>
            </el-row>
        </el-dialog>
        <div class="sidebar">
            <div class="sidebarItem borderBottom" @click="toBeMember()">
                <img src="../assets/images/tool/member.png" alt="">
                <div>
                    成为会员
                </div>
            </div>
            <el-popover ref="popover" placement="left" width="220" trigger="hover" popper-class="moreSettingDiv">
                <template #reference>
                    <div class="sidebarItem">
                        <img src="../assets/images/tool/service.png" alt="">
                        <div>
                            联系客服
                        </div>
                    </div>
                </template>
                <div class="serviceCodeBox">
                    <div class="topColor">
                        <img src="../assets/images/tool/serviceColor.png" alt="">联系客服
                    </div>
                    <img style="width: 174px; " src="../assets/images/tool/WeChactCode.png" alt="">
                    <div style="cursor: pointer;" v-clipboard:copy="userInfoDetail.userName" v-clipboard:success="firstCopySuccess"
                        v-clipboard:error="firstCopyError">
                        您的ID：{{userInfoDetail.userName}}</div>
                    <div style="font-size:12px">受馈问题时，请告知客服您的ID</div>
                </div>
            </el-popover>
        </div>
        <!-- 弹窗 -->
        <payMemberCard @payEnd='payEnd'></payMemberCard>

    </div>
</template>
<script>
import toolBox from "@/api/toolBox";
import { phoneLogin, sendSms, getUserInfo } from "@/api/login";
import { mapState } from 'vuex'
import { getToken } from '@/utils/auth'
export default {
    data() {
        return {
            isToken: localStorage.getItem('isToken') === 'true',
            userPhone: localStorage.getItem('userPhone') || '',
            loginModalVisible: false,
            searchTerm: '',
            activeFilter: 'all',
            dialogPayMemberCard: false,
            captchaButton: null,

            loginForm: {
                phone: '',
                code: ''
            },

            rules: {
                phone: [
                    { required: true, message: "手机号码不能为空", trigger: "blur" }
                ],
                code: [
                    { required: true, message: "验证码不能为空", trigger: "blur" }
                ]
            },

            captcha: null,
            captchaButton: null,
            isPhone: false,
            isCodeSent: false,
            isCodeSentSecond: 60,
            sceneId: '129ze0ev',
            userInfoDetail: {},
            freeTimesValue: ''
        };
    },
    computed: {
        userInfo() {
            return this.$store.state.user.userInfo;
        },
        freeTimes() {
            return this.$store.state.user.freeTimes;
        }
    },
    watch: {
        userInfo(newVal, oldVal) {
            // console.log(`userInfo changed from ${oldVal} to ${newVal}`);
            this.userInfoDetail = newVal ? newVal : {}
            // 在这里执行你的逻辑
        },
        freeTimes(newVal, oldVal) {
            console.log(`freeTimes changed from ${oldVal} to ${newVal}`);
            this.freeTimesValue = newVal ? newVal : {}
            // 在这里执行你的逻辑
        }
    },
    mounted() {
        // console.log(this.$store.state.user.userInfo)
        console.log('无畏是青春的态度，热AI是时代的脉搏。各位新同学正以无畏的姿态奔赴通用人工智能的星辰大海！\n作为引领AI时代浪潮的主力军，广阔舞台，待你大展身手。\n乘风破浪，勇往直前，未来百度将与你一起，创造无限可能！\n简历投递：17647390219@163.com');
        this.getUserInfoM();
        this.agentSupport().then(val => {
            this.freeTimesValue = val.msg
            this.$store.dispatch("setFreeTimes", val.msg)
        })
    },
    beforeUnmount() {
        this.captchaButton = null;

        // 必须删除相关元素，否则再次mount多次调用 initAliyunCaptcha 会导致多次回调 captchaVerifyCallback
        document.getElementById('aliyunCaptcha-mask')?.remove();
        document.getElementById('aliyunCaptcha-window-popup')?.remove();
    },
    methods: {
        // 复制
        firstCopySuccess() {
            this.$modal.msgSuccess("已复制");
        },
        firstCopyError() {
            this.$modal.msgError("复制失败");
        },
        // 成为会员
        toBeMember() {
            let that = this
            if (getToken()) {
                this.$store.dispatch("setDialogPayMemberCard", true)
            } else {
                this.handleToolClick();
            }
        },
        // 关闭支付弹窗
        payEnd() {
            this.dialogPayMemberCard = false
        },
        getInstance(instance) {
            this.captcha = instance;
        },
        async captchaVerifyCallback(captchaVerifyParam) {
            // 1.向后端发起业务请求，获取验证码验证结果和业务结果
            const captcha = await toolBox.verifyCaptcha({
                captchaVerifyParam: captchaVerifyParam,
                sceneId: this.sceneId
            }).then(response => {
                return response
            }).catch(err => {
                return {
                    captchaResult: false,
                    bizResult: false,
                }
            });
            if (captcha.code == 200 && captcha.data) {

                this.sendCode()
                return {
                    captchaResult: true,
                    bizResult: true,
                }

            }
            else {
                return {
                    captchaResult: false,
                    bizResult: false,
                }
            }
            console.log('关闭');

        },
        // 验证通过后调用
        onBizResultCallback() {
            console.log('onBizResultCallback');
        },

        initUserState() {
            this.isToken = localStorage.getItem('isToken') === 'true';
            this.userPhone = localStorage.getItem('userPhone') || '';
        },
        // 点击工具单条
        handleToolClick(toolId) {
            let that = this
            this.showLoginModal();
            this.startQrcodeCheck();
            if (this.$refs.loginForm) {
                this.$refs.loginForm.resetFields(); // 清空表单数据
                // 手动重置验证状态
                Object.keys(this.rules).forEach(key => {
                    if (this.$refs.loginForm.fields[key]) {

                        this.$refs.loginForm.fields[key].validateState = ''; // 重置验证状态
                    }
                });

            }

            this.captchaButton = document.getElementById('captcha-button');

            window.initAliyunCaptcha({
                SceneId: that.sceneId, // 场景ID。根据步骤二新建验证场景后，您可以在验证码场景列表，获取该场景的场景ID
                prefix: 'ewdtip', // 身份标。开通阿里云验证码2.0后，您可以在控制台概览页面的实例基本信息卡片区域，获取身份标
                mode: 'popup', // 验证码模式。popup表示要集成的验证码模式为弹出式。无需修改
                element: '#captcha-element', // 页面上预留的渲染验证码的元素，与原代码中预留的页面元素保持一致。
                button: '#captcha-button', // 触发验证码弹窗的元素。button表示单击登录按钮后，触发captchaVerifyCallback函数。您可以根据实际使用的元素修改element的值
                captchaVerifyCallback: this.captchaVerifyCallback, // 业务请求(带验证码校验)回调函数，无需修改
                onBizResultCallback: this.onBizResultCallback, // 业务请求结果回调函数，无需修改
                getInstance: this.getInstance, // 绑定验证码实例函数，无需修改
                slideStyle: {
                    width: 360,
                    height: 40,
                }, // 滑块验证码样式，支持自定义宽度和高度，单位为px。其中，width最小值为320 px
                language: 'cn', // 验证码语言类型，支持简体中文（cn）、繁体中文（tw）、英文（en）
            });
        },
        showLoginModal() {
            this.loginModalVisible = true;
        },
        hideLoginModal() {
            this.loginModalVisible = false;
            this.stopQrcodeCheck();
        },
        startQrcodeCheck() {
            this.qrcodeStatus = true;
            // setTimeout(() => {
            //   this.qrcodeStatus = false;
            //   this.handleWechatLogin({
            //     nickname: '微信用户',
            //     avatar: 'https://thirdwx.qlogo.cn/mmopen/vi_32/POgEwh4mIHO4nibH0KlMECNjjGxQUq24ZEaH4uWkAYZf7Y7U6vq6JFSicwZD3vLiaUuRqKJNYCqVS6hdibiaAKqN5aQ/132'
            //   });
            // }, 5000); // 模拟5秒后扫码成功
        },
        stopQrcodeCheck() {
            this.qrcodeStatus = false;
        },
        handleWechatLogin(user) {
            this.isToken = true;
            localStorage.setItem('isToken', 'true');
            localStorage.setItem('userInfo', JSON.stringify(user));
            this.hideLoginModal();
            this.initUserState();
            alert(`微信用户 ${user.nickname} 登录成功`);
        },
        sendCode() {
            this.isCodeSentSecond == 60
            sendSms({
                phone: this.loginForm.phone,
            }).then(response => {
                if (response.code == 200) {
                    this.$modal.msgSuccess("发送成功");
                    this.codeSentTime = setInterval(() => {
                        this.isCodeSent = true;
                        this.isCodeSentSecond--
                        if (this.isCodeSentSecond == 0) {
                            this.isCodeSent = false;
                            clearInterval(this.codeSentTime)
                        }
                    }, 1000)
                }

            });
        },
        getUserInfoM() {
            console.log(getToken());
            if (getToken()) {
                getUserInfo().then(val => {
                    if (val.code == 200) {
                        this.userInfoDetail = val.data
                        this.$store.dispatch('setUserInfo', val.data)
                    }
                }).catch(err => {
                    this.$store.dispatch('LogOut').then(() => {
                        this.userInfoDetail = ''
                    }).catch(() => {
                    });
                })
            }
            else {

                this.$store.dispatch('LogOut').then(() => {
                    this.userInfoDetail = ''
                }).catch(() => {
                });
            }
        },
        doLogin() {
            // 登录逻辑
            let that = this
            this.$refs["loginForm"].validate(valid => {
                if (valid) {

                    this.$store.dispatch("LoginPhone", {
                        phone: that.loginForm.phone,
                        code: that.loginForm.code,
                    }).then(() => {
                        // this.isToken = true;
                        this.hideLoginModal();
                        this.initUserState();
                        this.$modal.msgSuccess("登录成功");
                        this.getUserInfoM()

                    }).catch(() => {
                        this.hideLoginModal();
                    });
                }
            });
        },
        // 校验手机号是否正确
        setIsPhone(e) {
            const reg = /^1[3456789]\d{9}$/;
            if (reg.test(e)) {
                this.isPhone = true
            }
            else {
                this.isPhone = false
            }
        },
        // 退出登录
        logout() {
            this.$store.dispatch('LogOut').then(() => {
                this.$modal.msgSuccess("操作成功");
                this.userInfoDetail = ''
                this.$router.replace({ path: '/' });
            }).catch(() => {
            });
        },
        goBackHome() {
            this.$router.replace({ path: '/' });
        }

    },
};
</script>
<style lang="scss">
.serviceCodeBox {
    // background-color: #40ffa6;
    padding: 10px;
}
.serviceCodeBox .topColor {
    display: flex;
    padding: 10px;
    font-weight: 600;
    font-size: 16px;
    img {
        width: 20px;
        margin-right: 10px;
    }
}
</style>
<style lang="scss" scoped>
@import url("https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css");
:root {
    --primary: #6366f1;
    --secondary: #8b5cf6;
    --accent: #ec4899;
    --glass: rgba(255, 255, 255, 0.95);
}

body {
    background: linear-gradient(45deg, #f3f4ff, #fdf2f8);
    min-height: 100vh;
    overflow: hidden;
}
.toolBox {
    min-width: 1000px;
    height: 100vh;
    overflow: hidden;
    .loginDialog {
        ::v-deep .el-dialog {
            margin-top: calc((100vh - 430px) / 2) !important;
        }
    }
    // position: relative;
    .sidebar {
        position: absolute;
        z-index: 10;
        right: 0;
        top: calc((100vh - 60px) / 2);
        box-shadow: 0 2px 14px 0 rgba(2, 89, 109, 0.14);
        border-radius: 5px 0 0 5px;
        border: #ebebeb solid 1px;
        background-color: #fff;
        .sidebarItem {
            padding: 15px;
            font-size: 12px;
            word-spacing: 2px;
            width: 62px;
            text-align: center;
            cursor: pointer;
            img {
                width: 20px;
                margin: 0 auto;
            }
        }
        .borderBottom {
            border-bottom: #ebebeb solid 1px;
        }
    }
    .header-content {
        display: flex;
        justify-content: space-between;
        align-items: center;
        color: rgb(0, 0, 0);
        // background: linear-gradient(135deg, var(--primary), var(--secondary));
        padding: 0rem 2rem;
        height: 60px;
        box-shadow: 0 2px 14px 0 rgba(2, 89, 109, 0.14);
        // box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);

        border-bottom: #ebebeb solid 1px;
        background-color: #fff;
        .logoText {
            height: 40px;
            cursor: pointer;
        }
        .el-dropdown {
            // color: #fff;
            .name {
                margin-left: 20px;
            }
        }
    }

    .el-header {
        background: linear-gradient(135deg, var(--primary), var(--secondary));
        //   padding: 1rem 2rem;
        box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
    }

    .user-info {
        display: flex;
        gap: 1.5rem;
        align-items: center;
        .name {
            cursor: pointer;
        }
        .toBeMember {
            cursor: pointer;
        }
        .freeTimesValue {
            font-size: 14px;
        }
    }
    .contentBox {
        display: flex;
        height: calc(100vh - 60px);
        width: 100%;
    }

    .action-buttons {
        display: flex;
        gap: 1rem;
        margin-top: 1rem;
    }

    .action-btn {
        display: flex;
        align-items: center;
        gap: 0.5rem;
        padding: 0.5rem 1rem;
        border-radius: 999px;
        cursor: pointer;
        transition: all 0.2s ease;
        background: rgba(236, 72, 153, 0.1);
        color: var(--accent);
        border: none;

        &:hover {
            background: var(--accent);
            color: white;
            transform: scale(1.05);
        }
    }

    @keyframes fadeIn {
        from {
            opacity: 0;
            transform: translateY(10px);
        }
        to {
            opacity: 1;
            transform: translateY(0);
        }
    }

    @media (max-width: 768px) {
        .el-aside {
            display: none;
        }
    }
    .qrcodeBox {
        .qrcode-wrapper {
            padding: 20px;
            border-right: 1px solid #e4e7ed;
        }

        .qrcode-header {
            text-align: center;
            margin-bottom: 20px;
        }

        .qrcode-header h3 {
            font-size: 18px;
            font-weight: 600;
            color: #333;
        }

        .qrcode-header p {
            font-size: 14px;
            color: #666;
        }

        .qrcode-content {
            position: relative;
            min-width: 160px;
            min-height: 160px;
            display: flex;
            justify-content: center;
            align-items: center;
        }

        .qrcode-image {
            width: 160px;
            height: 160px;
            margin: 0 auto;
            display: block;
        }

        .qrcode-status {
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(255, 255, 255, 0.9);
            display: flex;
            align-items: center;
            justify-content: center;
            flex-direction: column;
        }

        .qrcode-status i {
            font-size: 24px;
            color: #409eff;
            margin-bottom: 10px;
        }

        .qrcode-status span {
            font-size: 14px;
            color: #409eff;
        }

        .qrcode-footer {
            text-align: center;
            font-size: 14px;
            color: #666;
            margin-top: 20px;
        }

        .phone-login {
            padding: 20px;
        }

        .phone-login-header {
            text-align: center;
            margin-bottom: 30px;
        }

        .phone-login-header h2 {
            font-size: 24px;
            font-weight: bold;
            color: #333;
        }

        .login-button {
            width: 100%;
            margin-top: 20px;
        }
    }
}
</style>